//contect
ONE_KEY_SIZE=19.05;

const coverMM2pixel =(v)=>{
    return v/0.254;
}

const readLayoutJson = (json)=>{
    res=[]
    let nowLeft= 0;
    let nowTop= 0;
    let nextBtnWidth=1;
    let nextBtnHeight= 1;
    for(line of json) {
        for(key of line) {
            if(typeof key === 'string'){
                res.push({
                    keyName:key.toLowerCase(),
                    left:nowLeft+(nextBtnWidth-1)/2,
                    top:nowTop+(nextBtnHeight-1)/2
                })
                nowLeft+=nextBtnWidth
                nextBtnHeight=1;
                nextBtnWidth=1;
            }else{
                if(key.h){
                    nextBtnHeight=key.h;
                }
                if(key.w){
                    nextBtnWidth=key.w;
                }
                if(key.x){
                    nowLeft+=key.x;
                }
                if(key.y){
                    nowTop+=key.y;
                }
            }
        }
        nowTop++;
        nowLeft=0;
    }
    return res;
}

const searchKeyFootprintId = (pcb,keyMap,keyHead)=>{
    let keyNeed = keyMap.map(key=>{
        return key.keyName;
    })
    let footprints = pcb["FOOTPRINT"];
    let outMap = {};
    Object.keys(footprints).forEach(footprintId=>{
        let footprint = footprints[footprintId];
        Object.keys(footprint["TEXT"]).forEach(textId=>{
            let keyNameIndex = keyNeed.indexOf(footprint["TEXT"][textId].text.replace(keyHead,"").toLowerCase());
            if(keyNameIndex!=-1){
                outMap[keyNeed[keyNameIndex]] = footprintId;
            }
        }) 
    });
    return outMap;
}



alert("欢迎使用键盘自动化排布工具");
let layout = prompt("请输入布局文件");
console.log(layout);
layout = JSON.parse(layout);
console.log(layout);
let keyMap=[];
try{
    keyMap = readLayoutJson(layout);
    console.log(keyMap);    
}catch(e){
    console.log(e.message);
    alert("layout decode fail please check your layout json");
}

let keyHead = prompt("请输入按键前缀");


let pcb = api('getSource', {type:'json'});

let layoutKeyMapping = searchKeyFootprintId(pcb, keyMap,keyHead);

console.log(layoutKeyMapping);

firstKey = pcb["FOOTPRINT"][layoutKeyMapping[keyMap[0].keyName]];

firstKeyTop = firstKey.head.y;
firstKeyLeft = firstKey.head.x;

for(i=1;i<keyMap.length;i++){
    api('moveObjsTo', {
        objs:[{gId:layoutKeyMapping[keyMap[i].keyName]}],
        y:firstKeyTop+coverMM2pixel(keyMap[i].top*ONE_KEY_SIZE),
        x:firstKeyLeft+coverMM2pixel(keyMap[i].left*ONE_KEY_SIZE)});
}